<template>
  <div class="all-bookings">
    <a-card title="所有预定记录">
      <!-- 筛选器 -->
      <div class="filter-section">
        <a-space wrap>
          <a-select
            v-model:value="filters.roomId"
            placeholder="选择会议室"
            style="width: 200px"
            allowClear
            @change="fetchBookings"
          >
            <a-select-option value="">全部会议室</a-select-option>
            <a-select-option v-for="room in rooms" :key="room.id" :value="room.id">
              {{ room.name }}
            </a-select-option>
          </a-select>

          <a-select
            v-model:value="filters.status"
            placeholder="选择状态"
            style="width: 150px"
            allowClear
            @change="fetchBookings"
          >
            <a-select-option value="">全部状态</a-select-option>
            <a-select-option value="PENDING">待确认</a-select-option>
            <a-select-option value="CONFIRMED">已确认</a-select-option>
            <a-select-option value="CANCELLED">已取消</a-select-option>
            <a-select-option value="COMPLETED">已完成</a-select-option>
          </a-select>

          <a-input
            v-model:value="filters.bookingPerson"
            placeholder="预定人姓名"
            style="width: 150px"
            allowClear
            @change="fetchBookings"
          />

          <a-button type="primary" @click="fetchBookings">
            <template #icon><SearchOutlined /></template>
            查询
          </a-button>

          <a-button @click="resetFilters">
            <template #icon><ReloadOutlined /></template>
            重置
          </a-button>
        </a-space>
      </div>

      <!-- 预定列表表格 -->
      <a-table
        :columns="columns"
        :data-source="bookings"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        class="mt-4"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'room'">
            <a-tag color="blue">{{ record.room_name }}</a-tag>
          </template>

          <template v-if="column.key === 'time'">
            <div>
              <div>{{ formatDate(record.start_time) }}</div>
              <div class="text-secondary">
                {{ formatTime(record.start_time) }} - {{ formatTime(record.end_time) }}
              </div>
            </div>
          </template>

          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>

          <template v-if="column.key === 'action'">
            <a-space>
              <a-button
                type="primary"
                size="small"
                v-if="record.status === 'PENDING'"
                @click="confirmBooking(record)"
              >
                确认
              </a-button>
              <a-button
                danger
                size="small"
                v-if="record.status !== 'CANCELLED'"
                @click="cancelBooking(record)"
              >
                取消
              </a-button>
              <a-button type="link" size="small" @click="viewDetails(record)">
                详情
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="detailsVisible"
      title="预定详情"
      :footer="null"
      width="600px"
    >
      <a-descriptions bordered v-if="selectedBooking">
        <a-descriptions-item label="会议室" :span="3">
          {{ selectedBooking.room_name }}
        </a-descriptions-item>
        <a-descriptions-item label="预定人" :span="3">
          {{ selectedBooking.booking_person }}
        </a-descriptions-item>
        <a-descriptions-item label="会议内容" :span="3">
          {{ selectedBooking.meeting_content }}
        </a-descriptions-item>
        <a-descriptions-item label="开始时间" :span="3">
          {{ formatDateTime(selectedBooking.start_time) }}
        </a-descriptions-item>
        <a-descriptions-item label="结束时间" :span="3">
          {{ formatDateTime(selectedBooking.end_time) }}
        </a-descriptions-item>
        <a-descriptions-item label="状态" :span="3">
          <a-tag :color="getStatusColor(selectedBooking.status)">
            {{ getStatusText(selectedBooking.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间" :span="3">
          {{ formatDateTime(selectedBooking.created_at) }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import api from '../services/api'
import dayjs from 'dayjs'

// 数据
const bookings = ref([])
const rooms = ref([])
const loading = ref(false)
const detailsVisible = ref(false)
const selectedBooking = ref(null)

// 筛选条件
const filters = reactive({
  roomId: '',
  status: '',
  bookingPerson: ''
})

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格列定义
const columns = [
  {
    title: '会议室',
    key: 'room',
    width: 100
  },
  {
    title: '预定人',
    dataIndex: 'booking_person',
    key: 'booking_person',
    width: 100
  },
  {
    title: '会议内容',
    dataIndex: 'meeting_content',
    key: 'meeting_content',
    ellipsis: true
  },
  {
    title: '时间',
    key: 'time'
  },
  {
    title: '状态',
    key: 'status',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

// 获取预定列表
const fetchBookings = async () => {
  loading.value = true
  
  try {
    const params = {
      skip: (pagination.current - 1) * pagination.pageSize,
      limit: pagination.pageSize
    }
    
    if (filters.roomId) params.room_id = filters.roomId
    if (filters.status) params.status = filters.status
    if (filters.bookingPerson) params.booking_person = filters.bookingPerson
    
    const response = await api.get('/bookings', { params })
    bookings.value = response.data
    // Note: 实际应用中应该有total字段
    pagination.total = response.data.length
  } catch (error) {
    message.error('获取预定列表失败')
  } finally {
    loading.value = false
  }
}

// 获取会议室列表
const fetchRooms = async () => {
  try {
    const response = await api.get('/rooms')
    rooms.value = response.data
  } catch (error) {
    message.error('获取会议室列表失败')
  }
}

// 重置筛选
const resetFilters = () => {
  filters.roomId = ''
  filters.status = ''
  filters.bookingPerson = ''
  pagination.current = 1
  fetchBookings()
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchBookings()
}

// 确认预定
const confirmBooking = async (booking) => {
  try {
    await api.put(`/bookings/${booking.id}`, {
      ...booking,
      status: 'CONFIRMED'
    })
    message.success('预定已确认')
    fetchBookings()
  } catch (error) {
    message.error('操作失败')
  }
}

// 取消预定
const cancelBooking = (booking) => {
  Modal.confirm({
    title: '确认取消',
    content: '确定要取消这个预定吗？',
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      try {
        await api.delete(`/bookings/${booking.id}`)
        message.success('预定已取消')
        fetchBookings()
      } catch (error) {
        message.error('取消失败')
      }
    }
  })
}

// 查看详情
const viewDetails = (booking) => {
  selectedBooking.value = booking
  detailsVisible.value = true
}

// 状态颜色
const getStatusColor = (status) => {
  const colors = {
    PENDING: 'orange',
    CONFIRMED: 'green',
    CANCELLED: 'red',
    COMPLETED: 'blue'
  }
  return colors[status] || 'default'
}

// 状态文本
const getStatusText = (status) => {
  const texts = {
    PENDING: '待确认',
    CONFIRMED: '已确认',
    CANCELLED: '已取消',
    COMPLETED: '已完成'
  }
  return texts[status] || status
}

// 日期格式化
const formatDate = (dateStr) => {
  return dayjs(dateStr).format('YYYY-MM-DD')
}

const formatTime = (dateStr) => {
  return dayjs(dateStr).format('HH:mm')
}

const formatDateTime = (dateStr) => {
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss')
}

// 初始化
onMounted(() => {
  fetchRooms()
  fetchBookings()
})
</script>

<style scoped>
.filter-section {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.text-secondary {
  color: #8c8c8c;
  font-size: 12px;
}
</style>